<template>
  <div class="income-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>收入统计</span>
          <el-button-group>
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
            <el-button type="success" @click="exportData">导出数据</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="stat-header">
                <span>今日收入</span>
                <el-tag type="success"
                  >{{ compareWithYesterday >= 0 ? "+" : ""
                  }}{{ compareWithYesterday }}%</el-tag
                >
              </div>
            </template>
            <div class="stat-content">
              <div class="stat-amount">¥{{ todayIncome.toFixed(2) }}</div>
              <div class="stat-desc">较昨日</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="stat-header">
                <span>本月收入</span>
                <el-tag type="success"
                  >{{ compareWithLastMonth >= 0 ? "+" : ""
                  }}{{ compareWithLastMonth }}%</el-tag
                >
              </div>
            </template>
            <div class="stat-content">
              <div class="stat-amount">¥{{ monthIncome.toFixed(2) }}</div>
              <div class="stat-desc">较上月</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="stat-header">
                <span>本年收入</span>
                <el-tag type="success"
                  >{{ compareWithLastYear >= 0 ? "+" : ""
                  }}{{ compareWithLastYear }}%</el-tag
                >
              </div>
            </template>
            <div class="stat-content">
              <div class="stat-amount">¥{{ yearIncome.toFixed(2) }}</div>
              <div class="stat-desc">较去年</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="stat-header">
                <span>总收入</span>
              </div>
            </template>
            <div class="stat-content">
              <div class="stat-amount">¥{{ totalIncome.toFixed(2) }}</div>
              <div class="stat-desc">累计收入</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <div class="chart-section">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>收入趋势</span>
              <el-radio-group v-model="chartTimeRange" size="small">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
                <el-radio-button label="year">近12个月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <div ref="incomeChart" style="width: 100%; height: 400px"></div>
          </div>
        </el-card>
      </div>

      <!-- 收入分类统计 -->
      <div class="category-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>收入分类占比</span>
                  <el-select v-model="categoryTimeRange" size="small">
                    <el-option label="今日" value="today" />
                    <el-option label="本周" value="week" />
                    <el-option label="本月" value="month" />
                    <el-option label="本年" value="year" />
                  </el-select>
                </div>
              </template>
              <div class="chart-container">
                <div
                  ref="categoryChart"
                  style="width: 100%; height: 300px"
                ></div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>支付方式分布</span>
                  <el-select v-model="paymentTimeRange" size="small">
                    <el-option label="今日" value="today" />
                    <el-option label="本周" value="week" />
                    <el-option label="本月" value="month" />
                    <el-option label="本年" value="year" />
                  </el-select>
                </div>
              </template>
              <div class="chart-container">
                <div
                  ref="paymentChart"
                  style="width: 100%; height: 300px"
                ></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 收入明细 -->
      <div class="income-details">
        <el-card>
          <template #header>
            <div class="detail-header">
              <span>收入明细</span>
              <div class="header-actions">
                <!-- 搜索表单 -->
                <el-form :inline="true" :model="searchForm">
                  <el-form-item label="收入类型">
                    <el-select
                      v-model="searchForm.type"
                      placeholder="请选择收入类型"
                    >
                      <el-option label="门票收入" value="ticket" />
                      <el-option label="酒店收入" value="hotel" />
                      <el-option label="套餐收入" value="package" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="时间范围">
                    <el-date-picker
                      v-model="searchForm.dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSearch"
                      >搜索</el-button
                    >
                    <el-button @click="resetSearch">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </template>

          <!-- 明细表格 -->
          <el-table v-loading="loading" :data="incomeList" style="width: 100%">
            <el-table-column prop="orderNo" label="订单编号" width="180" />
            <el-table-column prop="type" label="收入类型" width="120">
              <template #default="{ row }">
                <el-tag>{{ getIncomeTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="收入金额" width="120">
              <template #default="{ row }">
                ¥{{ row.amount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="paymentMethod"
              label="支付方式"
              width="120"
            />
            <el-table-column
              prop="productName"
              label="商品名称"
              min-width="200"
              show-overflow-tooltip
            />
            <el-table-column prop="createTime" label="创建时间" width="160" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusTag(row.status)">
                  {{ getStatusLabel(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="viewDetail(row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>

          <template #empty>
            <div class="empty-state">
              <el-empty 
                description="暂无收入数据" 
                :image-size="200"
              >
                <div class="empty-text">暂无收入明细数据</div>
                <div class="empty-subtext">有收入交易后将在此处显示</div>
              </el-empty>
            </div>
          </template>
        </el-card>
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="收入详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{
          currentIncome.orderNo
        }}</el-descriptions-item>
        <el-descriptions-item label="收入类型">
          <el-tag>{{ getIncomeTypeLabel(currentIncome.type) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="收入金额"
          >¥{{ currentIncome.amount?.toFixed(2) }}</el-descriptions-item
        >
        <el-descriptions-item label="支付方式">{{
          currentIncome.paymentMethod
        }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{
          currentIncome.productName
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          currentIncome.createTime
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTag(currentIncome.status)">
            {{ getStatusLabel(currentIncome.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{
          currentIncome.remark || "无"
        }}</el-descriptions-item>
      </el-descriptions>

      <div class="order-info mt-4">
        <h4>订单信息</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="下单用户">{{
            currentIncome.userName
          }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{
            currentIncome.userPhone
          }}</el-descriptions-item>
          <el-descriptions-item label="使用时间">{{
            currentIncome.useTime
          }}</el-descriptions-item>
          <el-descriptions-item label="购买数量">{{
            currentIncome.quantity
          }}</el-descriptions-item>
          <el-descriptions-item label="单价"
            >¥{{ currentIncome.unitPrice?.toFixed(2) }}</el-descriptions-item
          >
          <el-descriptions-item label="优惠金额"
            >¥{{
              currentIncome.discountAmount?.toFixed(2)
            }}</el-descriptions-item
          >
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import service from "@/api/axios";
import * as XLSX from "xlsx";

// 统计数据
const todayIncome = ref(0);
const monthIncome = ref(0);
const yearIncome = ref(0);
const totalIncome = ref(0);
const compareWithYesterday = ref(0);
const compareWithLastMonth = ref(0);
const compareWithLastYear = ref(0);

// 图表相关
const chartTimeRange = ref("week");
const categoryTimeRange = ref("month");
const paymentTimeRange = ref("month");
const incomeChart = ref(null);
const categoryChart = ref(null);
const paymentChart = ref(null);
let incomeChartInstance = null;
let categoryChartInstance = null;
let paymentChartInstance = null;

// 搜索表单
const searchForm = reactive({
  type: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const incomeList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 详情对话框
const detailDialogVisible = ref(false);
const currentIncome = ref({});

// API请求相关
// 获取收入统计数据
const fetchIncomeStatistics = async () => {
  try {
    const res = await service.get('/finance/income/statistics');
    if (res.code === 200 && res.data) {
      todayIncome.value = res.data.todayIncome || 0;
      monthIncome.value = res.data.monthIncome || 0;
      yearIncome.value = res.data.yearIncome || 0;
      totalIncome.value = res.data.totalIncome || 0;
      compareWithYesterday.value = res.data.compareWithYesterday || 0;
      compareWithLastMonth.value = res.data.compareWithLastMonth || 0;
      compareWithLastYear.value = res.data.compareWithLastYear || 0;
    } else {
      // 使用模拟数据
      todayIncome.value = 3562.50;
      monthIncome.value = 56280.75;
      yearIncome.value = 458920.25;
      totalIncome.value = 1258630.80;
      compareWithYesterday.value = 12.5;
      compareWithLastMonth.value = 8.3;
      compareWithLastYear.value = 15.8;
    }
  } catch (error) {
    console.error("获取收入统计数据失败", error);
    // 使用模拟数据
    todayIncome.value = 3562.50;
    monthIncome.value = 56280.75;
    yearIncome.value = 458920.25;
    totalIncome.value = 1258630.80;
    compareWithYesterday.value = 12.5;
    compareWithLastMonth.value = 8.3;
    compareWithLastYear.value = 15.8;
  }
};

// 获取收入明细列表
const fetchIncomeList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      type: searchForm.type || undefined,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    };
    
    const res = await service.get('/finance/income/list', { params });
    if (res.code === 200 && res.data) {
      incomeList.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      // 使用模拟数据
      incomeList.value = [
        {
          id: 1,
          orderNo: "OR202403010001",
          type: "ticket",
          amount: 199.00,
          paymentMethod: "微信支付",
          productName: "贵港市古镇门票",
          createTime: "2024-03-01 10:30:25",
          status: "success",
          remark: "单人票",
          userName: "张三",
          userPhone: "13800138000",
          useTime: "2024-03-05",
          quantity: 1,
          unitPrice: 199.00,
          discountAmount: 0
        },
        {
          id: 2,
          orderNo: "OR202403010002",
          type: "hotel",
          amount: 688.00,
          paymentMethod: "支付宝",
          productName: "贵港大酒店豪华套房",
          createTime: "2024-03-01 11:45:18",
          status: "success",
          remark: "加床服务",
          userName: "李四",
          userPhone: "13900139000",
          useTime: "2024-03-10",
          quantity: 1,
          unitPrice: 688.00,
          discountAmount: 0
        },
        {
          id: 3,
          orderNo: "OR202403010003",
          type: "package",
          amount: 1288.00,
          paymentMethod: "银联",
          productName: "贵港文化体验二日游",
          createTime: "2024-03-01 14:20:36",
          status: "pending",
          remark: "两人行程",
          userName: "王五",
          userPhone: "13700137000",
          useTime: "2024-03-15",
          quantity: 2,
          unitPrice: 699.00,
          discountAmount: 110.00
        }
      ];
      total.value = incomeList.value.length;
    }
  } catch (error) {
    console.error("获取收入明细失败", error);
    // 使用模拟数据
    incomeList.value = [
      {
        id: 1,
        orderNo: "OR202403010001",
        type: "ticket",
        amount: 199.00,
        paymentMethod: "微信支付",
        productName: "贵港市古镇门票",
        createTime: "2024-03-01 10:30:25",
        status: "success",
        remark: "单人票",
        userName: "张三",
        userPhone: "13800138000",
        useTime: "2024-03-05",
        quantity: 1,
        unitPrice: 199.00,
        discountAmount: 0
      },
      {
        id: 2,
        orderNo: "OR202403010002",
        type: "hotel",
        amount: 688.00,
        paymentMethod: "支付宝",
        productName: "贵港大酒店豪华套房",
        createTime: "2024-03-01 11:45:18",
        status: "success",
        remark: "加床服务",
        userName: "李四",
        userPhone: "13900139000",
        useTime: "2024-03-10",
        quantity: 1,
        unitPrice: 688.00,
        discountAmount: 0
      },
      {
        id: 3,
        orderNo: "OR202403010003",
        type: "package",
        amount: 1288.00,
        paymentMethod: "银联",
        productName: "贵港文化体验二日游",
        createTime: "2024-03-01 14:20:36",
        status: "pending",
        remark: "两人行程",
        userName: "王五",
        userPhone: "13700137000",
        useTime: "2024-03-15",
        quantity: 2,
        unitPrice: 699.00,
        discountAmount: 110.00
      }
    ];
    total.value = incomeList.value.length;
  } finally {
    loading.value = false;
  }
};

// 获取收入类型标签
const getIncomeTypeLabel = (type) => {
  const types = {
    ticket: "门票收入",
    hotel: "酒店收入",
    package: "套餐收入",
  };
  return types[type] || type;
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    success: "已完成",
    pending: "待结算",
    refunded: "已退款",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statuses = {
    success: "success",
    pending: "warning",
    refunded: "info",
  };
  return statuses[status] || "";
};

// 初始化收入趋势图表
const initIncomeChart = async () => {
  if (incomeChartInstance) {
    incomeChartInstance.dispose();
  }
  incomeChartInstance = echarts.init(incomeChart.value);
  
  // 显示加载状态
  incomeChartInstance.showLoading();
  
  try {
    // 从API获取数据
    const res = await service.get('/finance/income/trend', {
      params: { timeRange: chartTimeRange.value }
    });
    
    let xAxisData = [];
    let seriesData = {
      total: [],
      ticket: [],
      hotel: [],
      package: []
    };
    
    if (res.code === 200 && res.data) {
      xAxisData = res.data.xAxis || [];
      seriesData = res.data.series || {
        total: [],
        ticket: [],
        hotel: [],
        package: []
      };
    } else {
      // 使用模拟数据
      if (chartTimeRange.value === 'week') {
        xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        seriesData = {
          total: [120, 132, 101, 134, 90, 230, 210],
          ticket: [20, 82, 91, 34, 50, 130, 110],
          hotel: [50, 32, 1, 54, 30, 70, 30],
          package: [50, 18, 9, 46, 10, 30, 70]
        };
      } else if (chartTimeRange.value === 'month') {
        xAxisData = Array.from({length: 30}, (_, i) => `${i+1}日`);
        seriesData = {
          total: Array.from({length: 30}, () => Math.floor(Math.random() * 500 + 100)),
          ticket: Array.from({length: 30}, () => Math.floor(Math.random() * 200 + 50)),
          hotel: Array.from({length: 30}, () => Math.floor(Math.random() * 200 + 50)),
          package: Array.from({length: 30}, () => Math.floor(Math.random() * 150 + 20))
        };
      } else {
        xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        seriesData = {
          total: [3200, 4320, 3010, 5340, 3900, 3300, 4100, 5200, 4520, 4390, 5620, 6100],
          ticket: [1200, 1320, 901, 1340, 900, 1300, 1200, 1400, 1520, 1290, 1620, 1700],
          hotel: [1500, 2000, 1500, 2500, 2100, 1200, 1900, 2300, 2000, 2100, 2800, 3200],
          package: [500, 1000, 609, 1500, 900, 800, 1000, 1500, 1000, 1000, 1200, 1200]
        };
      }
    }
    
    const option = {
      tooltip: {
        trigger: "axis",
      },
      legend: {
        data: ["总收入", "门票收入", "酒店收入", "套餐收入"],
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: xAxisData,
      },
      yAxis: {
        type: "value",
        axisLabel: {
          formatter: (value) => {
            return '¥' + value;
          }
        }
      },
      series: [
        {
          name: "总收入",
          type: "line",
          stack: "Total",
          data: seriesData.total,
          areaStyle: {opacity: 0.1},
          emphasis: {focus: 'series'},
          smooth: true
        },
        {
          name: "门票收入",
          type: "line",
          stack: "分类",
          data: seriesData.ticket,
          emphasis: {focus: 'series'},
          smooth: true
        },
        {
          name: "酒店收入",
          type: "line",
          stack: "分类",
          data: seriesData.hotel,
          emphasis: {focus: 'series'},
          smooth: true
        },
        {
          name: "套餐收入",
          type: "line",
          stack: "分类",
          data: seriesData.package,
          emphasis: {focus: 'series'},
          smooth: true
        },
      ],
    };
    
    incomeChartInstance.hideLoading();
    incomeChartInstance.setOption(option);
  } catch (error) {
    console.error("获取收入趋势数据失败", error);
    
    // 使用模拟数据
    let xAxisData = [];
    let seriesData = {
      total: [],
      ticket: [],
      hotel: [],
      package: []
    };
    
    if (chartTimeRange.value === 'week') {
      xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      seriesData = {
        total: [120, 132, 101, 134, 90, 230, 210],
        ticket: [20, 82, 91, 34, 50, 130, 110],
        hotel: [50, 32, 1, 54, 30, 70, 30],
        package: [50, 18, 9, 46, 10, 30, 70]
      };
    } else if (chartTimeRange.value === 'month') {
      xAxisData = Array.from({length: 30}, (_, i) => `${i+1}日`);
      seriesData = {
        total: Array.from({length: 30}, () => Math.floor(Math.random() * 500 + 100)),
        ticket: Array.from({length: 30}, () => Math.floor(Math.random() * 200 + 50)),
        hotel: Array.from({length: 30}, () => Math.floor(Math.random() * 200 + 50)),
        package: Array.from({length: 30}, () => Math.floor(Math.random() * 150 + 20))
      };
    } else {
      xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
      seriesData = {
        total: [3200, 4320, 3010, 5340, 3900, 3300, 4100, 5200, 4520, 4390, 5620, 6100],
        ticket: [1200, 1320, 901, 1340, 900, 1300, 1200, 1400, 1520, 1290, 1620, 1700],
        hotel: [1500, 2000, 1500, 2500, 2100, 1200, 1900, 2300, 2000, 2100, 2800, 3200],
        package: [500, 1000, 609, 1500, 900, 800, 1000, 1500, 1000, 1000, 1200, 1200]
      };
    }
    
    const option = {
      tooltip: {
        trigger: "axis",
      },
      legend: {
        data: ["总收入", "门票收入", "酒店收入", "套餐收入"],
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: xAxisData,
      },
      yAxis: {
        type: "value",
        axisLabel: {
          formatter: (value) => {
            return '¥' + value;
          }
        }
      },
      series: [
        {
          name: "总收入",
          type: "line",
          stack: "Total",
          data: seriesData.total,
          areaStyle: {opacity: 0.1},
          emphasis: {focus: 'series'},
          smooth: true
        },
        {
          name: "门票收入",
          type: "line",
          stack: "分类",
          data: seriesData.ticket,
          emphasis: {focus: 'series'},
          smooth: true
        },
        {
          name: "酒店收入",
          type: "line",
          stack: "分类",
          data: seriesData.hotel,
          emphasis: {focus: 'series'},
          smooth: true
        },
        {
          name: "套餐收入",
          type: "line",
          stack: "分类",
          data: seriesData.package,
          emphasis: {focus: 'series'},
          smooth: true
        },
      ],
    };
    
    incomeChartInstance.hideLoading();
    incomeChartInstance.setOption(option);
  }
};

// 初始化收入分类图表
const initCategoryChart = async () => {
  if (categoryChartInstance) {
    categoryChartInstance.dispose();
  }
  categoryChartInstance = echarts.init(categoryChart.value);
  
  // 显示加载状态
  categoryChartInstance.showLoading();
  
  try {
    // 从API获取数据
    const res = await service.get('/finance/income/category', {
      params: { timeRange: categoryTimeRange.value }
    });
    
    let pieData = [];
    
    if (res.code === 200 && res.data) {
      pieData = res.data.pieData || [];
    } else {
      // 使用模拟数据
      pieData = [
        { value: 1048, name: "门票收入" },
        { value: 735, name: "酒店收入" },
        { value: 580, name: "套餐收入" },
      ];
    }
    
    const option = {
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b}: {c} ({d}%)"
      },
      legend: {
        orient: "vertical",
        left: "left",
      },
      series: [
        {
          name: "收入分类",
          type: "pie",
          radius: "50%",
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    
    categoryChartInstance.hideLoading();
    categoryChartInstance.setOption(option);
  } catch (error) {
    console.error("获取收入分类数据失败", error);
    
    // 使用模拟数据
    const pieData = [
      { value: 1048, name: "门票收入" },
      { value: 735, name: "酒店收入" },
      { value: 580, name: "套餐收入" },
    ];
    
    const option = {
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b}: {c} ({d}%)"
      },
      legend: {
        orient: "vertical",
        left: "left",
      },
      series: [
        {
          name: "收入分类",
          type: "pie",
          radius: "50%",
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    
    categoryChartInstance.hideLoading();
    categoryChartInstance.setOption(option);
  }
};

// 初始化支付方式图表
const initPaymentChart = async () => {
  if (paymentChartInstance) {
    paymentChartInstance.dispose();
  }
  paymentChartInstance = echarts.init(paymentChart.value);
  
  // 显示加载状态
  paymentChartInstance.showLoading();
  
  try {
    // 从API获取数据
    const res = await service.get('/finance/income/payment', {
      params: { timeRange: paymentTimeRange.value }
    });
    
    let pieData = [];
    
    if (res.code === 200 && res.data) {
      pieData = res.data.pieData || [];
    } else {
      // 使用模拟数据
      pieData = [
        { value: 1048, name: "微信支付" },
        { value: 735, name: "支付宝" },
        { value: 580, name: "银联" },
        { value: 484, name: "其他" },
      ];
    }
    
    const option = {
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b}: {c} ({d}%)"
      },
      legend: {
        orient: "vertical",
        left: "left",
      },
      series: [
        {
          name: "支付方式",
          type: "pie",
          radius: "50%",
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    
    paymentChartInstance.hideLoading();
    paymentChartInstance.setOption(option);
  } catch (error) {
    console.error("获取支付方式数据失败", error);
    
    // 使用模拟数据
    const pieData = [
      { value: 1048, name: "微信支付" },
      { value: 735, name: "支付宝" },
      { value: 580, name: "银联" },
      { value: 484, name: "其他" },
    ];
    
    const option = {
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b}: {c} ({d}%)"
      },
      legend: {
        orient: "vertical",
        left: "left",
      },
      series: [
        {
          name: "支付方式",
          type: "pie",
          radius: "50%",
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    
    paymentChartInstance.hideLoading();
    paymentChartInstance.setOption(option);
  }
};

// 刷新数据
const refreshData = () => {
  fetchIncomeStatistics();
  initIncomeChart();
  initCategoryChart();
  initPaymentChart();
  fetchIncomeList();
};

// 导出数据
const exportData = async () => {
  try {
    // 准备导出数据
    let dataToExport = [];
    
    try {
      // 尝试获取全部数据
      const res = await service.get('/finance/income/export');
      if (res.code === 200 && res.data) {
        dataToExport = res.data;
      } else {
        dataToExport = incomeList.value;
      }
    } catch (error) {
      console.error("获取导出数据失败", error);
      dataToExport = incomeList.value;
    }
    
    // 准备Excel数据
    const excelData = dataToExport.map(item => ({
      "订单编号": item.orderNo,
      "收入类型": getIncomeTypeLabel(item.type),
      "收入金额": item.amount.toFixed(2),
      "支付方式": item.paymentMethod,
      "商品名称": item.productName,
      "创建时间": item.createTime,
      "状态": getStatusLabel(item.status),
      "用户名": item.userName || "--",
      "联系电话": item.userPhone || "--",
      "使用时间": item.useTime || "--",
      "数量": item.quantity || "--",
      "单价": item.unitPrice ? item.unitPrice.toFixed(2) : "--",
      "优惠金额": item.discountAmount ? item.discountAmount.toFixed(2) : "--",
      "备注": item.remark || "--"
    }));
    
    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(excelData);
    
    // 设置列宽
    const columnWidths = [
      { wch: 20 }, // 订单编号
      { wch: 12 }, // 收入类型
      { wch: 12 }, // 收入金额
      { wch: 12 }, // 支付方式
      { wch: 30 }, // 商品名称
      { wch: 20 }, // 创建时间
      { wch: 10 }, // 状态
      { wch: 15 }, // 用户名
      { wch: 15 }, // 联系电话
      { wch: 20 }, // 使用时间
      { wch: 8 },  // 数量
      { wch: 10 }, // 单价
      { wch: 10 }, // 优惠金额
      { wch: 20 }  // 备注
    ];
    ws['!cols'] = columnWidths;
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "收入明细");
    
    // 生成Excel文件并下载
    XLSX.writeFile(wb, `收入明细_${new Date().toLocaleDateString()}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败：" + (error.message || "未知错误"));
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchIncomeList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 查看详情
const viewDetail = (row) => {
  currentIncome.value = row;
  detailDialogVisible.value = true;
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchIncomeList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchIncomeList();
};

// 监听图表容器大小变化
const handleResize = () => {
  incomeChartInstance?.resize();
  categoryChartInstance?.resize();
  paymentChartInstance?.resize();
};

// 监听图表参数变化，更新图表
watch(chartTimeRange, () => {
  initIncomeChart();
});

watch(categoryTimeRange, () => {
  initCategoryChart();
});

watch(paymentTimeRange, () => {
  initPaymentChart();
});

// 页面加载时初始化
onMounted(() => {
  fetchIncomeStatistics();
  fetchIncomeList();
  initIncomeChart();
  initCategoryChart();
  initPaymentChart();
  window.addEventListener("resize", handleResize);
});

// 页面卸载时清理
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  incomeChartInstance?.dispose();
  categoryChartInstance?.dispose();
  paymentChartInstance?.dispose();
});
</script>

<style scoped>
.income-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-content {
  text-align: center;
}

.stat-amount {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 10px 0;
}

.stat-desc {
  font-size: 12px;
  color: #909399;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  padding: 20px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mt-4 {
  margin-top: 20px;
}

/* 空状态样式 */
.empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}
</style>
